<template>
<view class="container">
  <!-- 顶部信息 -->
  <view class="header">
    <view class="header-item">
      <text class="label">水厂名称：</text>
      <picker :value="selectedPlantIndex" :range="waterPlants" @change="onPlantChange">
        <view class="picker">
          {{ waterPlants[selectedPlantIndex] }}
          <text class="arrow">▼</text>
        </view>
      </picker>
    </view>
    <view class="header-item">
      <text class="label">当前日期：</text>
      <text class="date">{{ createDate }}</text>
    </view>
  </view>

  <!-- 问题录入区 -->
  <view class="problems-section">
    <view v-for="(problem, idx) in problems" :key="problem.uid" class="problem-card">
      <view class="problem-header">
        <text class="problem-title">问题</text>
      </view>
      <view class="form-row">
        <text class="form-label">类型</text>
        <picker :value="problem.typeIndex" :range="problemTypes" @change="e => onTypeChange(e, idx)">
          <view class="picker">{{ problemTypes[problem.typeIndex] }}</view>
        </picker>
      </view>
      <view class="form-row">
        <text class="form-label">标题</text>
        <input v-model="problem.title" class="input" placeholder="请输入问题标题" maxlength="30"/>
      </view>
      <view class="form-row">
        <text class="form-label">描述</text>
        <textarea v-model="problem.description" class="textarea" placeholder="请输入问题描述" maxlength="200"/>
      </view>
      <view class="form-row">
        <text class="form-label">严重程度</text>
        <picker :value="problem.severityIndex" :range="severityOptions" @change="e => onSeverityChange(e, idx)">
          <view class="picker">{{ severityOptions[problem.severityIndex] }}</view>
        </picker>
      </view>
      <view class="form-row">
        <text class="form-label">建议完成期限</text>
        <picker mode="date" :value="problem.deadline" @change="e => onDeadlineChange(e, idx)">
          <view class="picker">{{ problem.deadline || '请选择日期' }}</view>
        </picker>
      </view>
      <view class="form-row">
        <text class="form-label">图片/视频</text>
        <button class="upload-btn" @click="chooseImage(idx)">上传图片</button>
        <button class="upload-btn" @click="chooseVideo(idx)">上传视频</button>
      </view>
      <view class="media-list">
        <image v-for="(img, i) in problem.images" :key="'img'+i" :src="img" class="media-thumb"/>
        <view v-for="(vid, i) in problem.videos" :key="'vid'+i" class="media-thumb video-thumb">🎬</view>
      </view>
    </view>
  </view>

  <!-- 保存按钮 -->
  <button class="save-btn" @click="saveOrder">保存整改单</button>
</view>
</template>

<script>
const sitesApi = uniCloud.importObject('sites');
const zhengaidanApi = uniCloud.importObject('zhengaidan');

function getToday() {
  const now = new Date();
  return now.getFullYear() + '-' +
    String(now.getMonth() + 1).padStart(2, '0') + '-' +
    String(now.getDate()).padStart(2, '0');
}

function genUid() {
  return Date.now().toString() + Math.random().toString(36).slice(2, 8);
}

export default {
  data() {
    return {
      selectedPlantIndex: 0,
      sites: [],
      waterPlants: [],
      createDate: getToday(),
      problemTypes: ['设备', '卫生', '安全', '其他'],
      severityOptions: ['严重', '一般'],
      problems: [
        {
          uid: genUid(),
          typeIndex: 0,
          title: '',
          description: '',
          severityIndex: 0,
          deadline: '',
          images: [],
          videos: []
        }
      ]
    }
  },
  created() {
    this.loadSites();
  },
  methods: {
    async loadSites() {
      try {
        const sitesRes = await sitesApi.getList();
        this.sites = sitesRes.data || [];
        this.waterPlants = this.sites.map(item => item.name);
      } catch (e) {
        uni.showToast({
          title: '站点加载失败',
          icon: 'none'
        });
      }
    },
    onPlantChange(e) {
      this.selectedPlantIndex = e.detail.value;
    },
    onTypeChange(e, idx) {
      this.problems[idx].typeIndex = e.detail.value;
    },
    onSeverityChange(e, idx) {
      this.problems[idx].severityIndex = e.detail.value;
    },
    onDeadlineChange(e, idx) {
      this.problems[idx].deadline = e.detail.value;
    },
    chooseImage(idx) {
      uni.chooseImage({
        count: 9,
        success: res => {
          this.problems[idx].images.push(...res.tempFilePaths);
        }
      });
    },
    chooseVideo(idx) {
      uni.chooseVideo({
        success: res => {
          this.problems[idx].videos.push(res.tempFilePath);
        }
      });
    },
    saveOrder() {
      // 校验
      for (const p of this.problems) {
        if (!p.title.trim()) {
          uni.showToast({ title: '请填写问题标题', icon: 'none' });
          return;
        }
        if (!p.deadline) {
          uni.showToast({ title: '请选择建议完成期限', icon: 'none' });
          return;
        }
      }
      // 构造整改单对象
      const p = this.problems[0];
      const site = this.sites[this.selectedPlantIndex];
      const order = {
        id: Date.now().toString(),
        waterPlantName: site ? site.name : '',
        plantId: site ? site._id : '',
        createDate: this.createDate,
        status: '待整改',
        type: this.problemTypes[p.typeIndex],
        title: p.title,
        description: p.description,
        severity: this.severityOptions[p.severityIndex],
        deadline: p.deadline,
        images: p.images,
        videos: p.videos,
        completionTime: ''
      };
      // 调用uniCloud云对象/云函数保存整改单
      uni.showLoading({ title: '提交中...' });
      zhengaidanApi.addOrder(order).then(res => {
        uni.hideLoading();
        uni.showToast({ title: '保存成功', icon: 'success' });
        setTimeout(() => {
          uni.switchTab({ url: '/pages/inspection/list' });
        }, 500);
      }).catch(err => {
        uni.hideLoading();
        uni.showToast({ title: '提交失败', icon: 'none' });
      });
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background: #f5f5f5;
  min-height: 100vh;
}
.header {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.1);
}
.header-item {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}
.label {
  font-size: 28rpx;
  color: #666;
  margin-right: 20rpx;
  min-width: 140rpx;
}
.picker {
  display: flex;
  align-items: center;
  color: #333;
  font-size: 28rpx;
}
.arrow {
  margin-left: 10rpx;
  color: #999;
  font-size: 24rpx;
}
.date {
  color: #333;
  font-size: 28rpx;
}
.problems-section {
  margin-bottom: 30rpx;
}
.problem-card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.08);
}
.problem-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.problem-title {
  font-size: 30rpx;
  font-weight: bold;
  color: #007AFF;
}
.del-btn {
  background: #ff4d4f;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
}
.form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18rpx;
}
.form-label {
  width: 140rpx;
  font-size: 26rpx;
  color: #666;
}
.input, .picker {
  flex: 1;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  font-size: 26rpx;
  margin-left: 10rpx;
  background: #fafafa;
}
.textarea {
  flex: 1;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 12rpx 20rpx;
  font-size: 26rpx;
  margin-left: 10rpx;
  background: #fafafa;
  min-height: 80rpx;
}
.upload-btn {
  background: #E8F4FD;
  color: #007AFF;
  border: 2rpx solid #007AFF;
  border-radius: 8rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  margin-right: 10rpx;
}
.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10rpx;
  margin-top: 10rpx;
}
.media-thumb {
  width: 80rpx;
  height: 80rpx;
  border-radius: 8rpx;
  background: #eee;
  object-fit: cover;
}
.video-thumb {
  display: flex;
  align-items: center;
  justify-content: center;
  background: #ddd;
  color: #666;
  font-size: 40rpx;
}
.add-problem-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  padding: 18rpx 40rpx;
  font-size: 28rpx;
  width: 220rpx;
  margin: 0 auto;
  display: block;
}
.save-btn {
  background: #007AFF;
  color: #fff;
  border: none;
  border-radius: 50rpx;
  padding: 25rpx;
  font-size: 30rpx;
  width: 100%;
  margin-top: 30rpx;
}
</style>